package com.yangl.corejava.net.support;


import com.yangl.corejava.util.Base64Util;

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Proxy.Type;

public class HttpProxy {
    HttpProxyConfig iproxy;
    private boolean authProxy;
    private boolean proxy;

    public HttpProxy(HttpProxyConfig proxy) {
        this.iproxy = proxy;
        if (proxy.getUsername() == null) {
            proxy.setUsername("");
        }

        if (proxy.getPassword() == null) {
            proxy.setPassword("");
        }

        String ip = proxy.getHost();
        if (ip != null && ip.length() > 1) {
            if (proxy.getUsername().length() <= 0 && proxy.getPassword().length() <= 0) {
                this.authProxy = false;
            } else {
                this.authProxy = true;
            }

            this.proxy = true;
        } else {
            this.proxy = false;
        }

    }

    public Proxy getProxy() {
        return new Proxy(Type.HTTP, new InetSocketAddress(this.iproxy.getHost(), this.iproxy.getPort()));
    }

    public boolean isAuthProxy() {
        return this.authProxy;
    }

    public boolean isProxy() {
        return this.proxy;
    }

    public String getBasicAuthString() {
        String auth = this.iproxy.getUsername() + ":" + this.iproxy.getPassword();
        return "Basic " + Base64Util.getBASE64(auth.getBytes());
    }

    public Authenticator getAuthenticator() {
        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(HttpProxy.this.iproxy.getUsername(), HttpProxy.this.iproxy.getPassword().toCharArray());
            }
        };
    }
}
